package com.jxwifi.cloud.quickclean.toolkit;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.idroid.widget.Toaster;
import com.jxwifi.cloud.quickclean.R;
import com.jxwifi.cloud.quickclean.adapter.PopKTListAdapter;
import com.jxwifi.cloud.quickclean.adapter.TkDetailsAdapter;
import com.jxwifi.cloud.quickclean.app.StateUtils;
import com.jxwifi.cloud.quickclean.app.UrlPool;
import com.jxwifi.cloud.quickclean.bean.PayParamsBean;
import com.jxwifi.cloud.quickclean.bean.ShopOrderDetailsBean;
import com.jxwifi.cloud.quickclean.bean.SystemBean;
import com.jxwifi.cloud.quickclean.model.AuzImpl;
import com.jxwifi.cloud.quickclean.okhttp.Params;
import com.jxwifi.cloud.quickclean.pay.PayResult;
import com.jxwifi.cloud.quickclean.pay.PayUtil;
import com.jxwifi.cloud.quickclean.popwindow.PopPayDepositModule;
import com.jxwifi.cloud.quickclean.utils.ToastUtils;
import com.popwindow.PopWindowUtil;
import com.popwindow.Popwindows;

import org.simple.eventbus.EventBus;

import java.util.List;

import cn.trinea.android.common.util.REPattern;

public class TKDetailsPresenter {

    private Context mContext;
    private TKDetailsView mView;
    private AuzImpl mAuz;

    private ShopOrderDetailsBean mDetailsBean;

    private TkDetailsAdapter mAdapter;
    private String mCustomer;

    public TKDetailsPresenter(Context context, TKDetailsView view) {
        this.mContext = context;
        this.mView = view;
        mAuz = new AuzImpl();
    }

    public void initData() {
        Params params = new Params();
        params.add("orderCode", mView.getTKOrder());
        mAuz.auzget(UrlPool.GET_SHOP_ORDER, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    mDetailsBean = JSON.parseObject(data, ShopOrderDetailsBean.class);
                    LoadData();
                } else {
                    mView.oninitData();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public void LoadData() {
        mView.getTkDetailsName().setText(mDetailsBean.getOrder().getShopProductTravalling().getReceiver());
        mView.getTkDetailsPhone().setText(mDetailsBean.getOrder().getShopProductTravalling().getReceiverTell());
        mView.getTkDetailsAddress().setText(mDetailsBean.getOrder().getShopProductTravalling().getReceiverAddr());
        mView.getTkDetailsPrice().setText("共" + mDetailsBean.getOrderContain().size() + "种商品 合计:\u00A5" + mDetailsBean.getOrder().getDiscountSumVal());
        mView.getTkDetailsStarts().setText(StateUtils.KtOrderStarts(mDetailsBean.getOrder().getShopProductTravalling().getStatus()));

        mView.getOrderNumber().setText(mDetailsBean.getOrder().getOrderCode());
        mView.getOrderTime().setText(mDetailsBean.getOrder().getCreateTime());

       /* mView.getDetailsRefund();//取消订单
        mView.getDetailsPayment();//付款
        mView.getDetailsReceiving();//确认收货
        mView.getDetailsLogistics();//查看物流
        mView.getDetailsStart();//状态布局*/

        if (StateUtils.PG_PAY.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus())) { //待付款
            mView.getDetailsPayment().setVisibility(View.VISIBLE);
            mView.getDetailsRefund().setVisibility(View.VISIBLE);
            mView.getDetailsReceiving().setVisibility(View.GONE);
            mView.getDetailsLogistics().setVisibility(View.GONE);
        } else if (StateUtils.TB_DELI.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus())) { //待发货
            mView.getDetailsRefund().setVisibility(View.VISIBLE);
            mView.getDetailsPayment().setVisibility(View.GONE);
            mView.getDetailsReceiving().setVisibility(View.GONE);
            mView.getDetailsLogistics().setVisibility(View.GONE);
        } else if (StateUtils.GTB_REC.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus())
                || StateUtils.SER_LEAVE.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus())) { //待收货 待确认收获
            mView.getDetailsRefund().setVisibility(View.GONE);
            mView.getDetailsPayment().setVisibility(View.GONE);
            mView.getDetailsReceiving().setVisibility(View.VISIBLE);
            mView.getDetailsLogistics().setVisibility(View.VISIBLE);
        } else if (StateUtils.SER_ARRIVE.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus()) ||
                StateUtils.OVER_TIME.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus()) ||
                StateUtils.CNL_ORDER.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus()) ||
                StateUtils.ADMIN_CNL_ORDER.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus()) ||
                StateUtils.ADMIN_RHB_MADE.equals(mDetailsBean.getOrder().getShopProductTravalling().getStatus())) { //已完成 订单超时  取消订单 后台取消订单 后台退款
            mView.getDetailsRefund().setVisibility(View.GONE);
            mView.getDetailsPayment().setVisibility(View.GONE);
            mView.getDetailsReceiving().setVisibility(View.GONE);
            mView.getDetailsLogistics().setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(mDetailsBean.getOrder().getShopProductTravalling().getDeliveryTime())) {
            mView.getOrderDeliver().setText(mDetailsBean.getOrder().getShopProductTravalling().getDeliveryTime());
        } else {
            mView.getDeliverTitle().setVisibility(View.GONE);
            mView.getOrderDeliver().setVisibility(View.GONE);
            mView.getOrderDeliver().setText("");
        }

        if (!TextUtils.isEmpty(mDetailsBean.getOrder().getShopProductTravalling().getLogisticsNum())) {
            mView.getOrderLogistics().setText(mDetailsBean.getOrder().getShopProductTravalling().getLogisticsNum());
        } else {
            mView.getLogisticsTitle().setVisibility(View.GONE);
            mView.getOrderLogistics().setVisibility(View.GONE);
            mView.getDetaliCopy().setVisibility(View.GONE);
            mView.getOrderLogistics().setText("");
        }

        if (!TextUtils.isEmpty(mDetailsBean.getOrder().getShopProductTravalling().getTravallingDesc())) {
            mView.getOrderLogisticsCompany().setText(mDetailsBean.getOrder().getShopProductTravalling().getTravallingDesc());
        } else {
            mView.getCompnyTitle().setVisibility(View.GONE);
            mView.getOrderLogisticsCompany().setVisibility(View.GONE);
            mView.getOrderLogisticsCompany().setText("");
        }

        mView.getRvList().setLayoutManager(new LinearLayoutManager(mContext));
        mView.getRvList().setAdapter(mAdapter = new TkDetailsAdapter(R.layout.list_details_kit_item, mDetailsBean.getOrderContain()));
        mAdapter.openLoadAnimation();
        mAdapter.openLoadAnimation(BaseQuickAdapter.FOOTER_VIEW);

        mView.getSvTkOrderDetails().setVisibility(View.VISIBLE);
    }

    //取消订单
    public void OrderCancel(){
        Params params=new Params();
        params.add("orderCode",mView.getTKOrder());
        mAuz.auzpost(UrlPool.POST_SHOP_REFUND, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code==0){
                    Toast toast = Toast.makeText(mContext, "订单已取消", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    initData();
                }else{
                    mView.onOrderCancel();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //支付布局
    public void paySetMeal() {
        PopPayDepositModule mPopPayOrder = new PopPayDepositModule(mContext, Double.valueOf(mDetailsBean.getOrder().getDiscountSumVal()), "支付金额", new PopPayDepositModule.PopPayListener() {
            @Override
            public void getPayOrder(String PayType, String PayPrice) {
                onPrePay(PayType);
            }
        });
        Popwindows window = PopWindowUtil.getPopupWindow(mPopPayOrder.getView(), ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.MATCH_PARENT);
        mPopPayOrder.setPopwindow(window);
        window.show(mView.getDeliverTitle(), Popwindows.Location.TOP);
    }

    public void onPrePay(String PayType){
        Params params=new Params();
        //params.add("addressId",mAddressId);
        params.add("orderCode",mDetailsBean.getOrder().getOrderCode());
        params.add("payChannelEnum",PayType);
        params.add("remark",mDetailsBean.getOrder().getRemarks());
        params.add("tradeType","APP");
        params.add("userName",mDetailsBean.getOrder().getShopProductTravalling().getReceiver());
        params.add("userTell",mDetailsBean.getOrder().getShopProductTravalling().getReceiverTell());

        mAuz.auzpost(UrlPool.POST_SHOP_PAY_SHOP, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                PayParamsBean mParams = JSON.parseObject(data, PayParamsBean.class);
                if (mParams.isNoPayment()){
                    EventBus.getDefault().post(new PayResult(true, mParams.getOutTradNo()), "e-PayResult");
                }else{
                    if (StateUtils.PAY_ALI.equals(mParams.getPayChannelEnum())) { //支付宝
                        PayUtil.getInstance().aliPay(mContext, mParams);
                    } else if (StateUtils.PAY_WX.equals(mParams.getPayChannelEnum())) { //微信
                        //mView.getWXPayCode(mParams.getOutTradNo());
                        PayUtil.getInstance().WXPay(mContext, mParams.getWxPayResult());
                    }
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //联系客服
    public void inittell() {
        Params params = new Params();
        mAuz.auzget(UrlPool.SYSTEM_LIST, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code == 0) {
                    List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                    for (int i = 0; i < msystemBean.size(); i++) {
                        if ("kjb_ke_tell".equals(msystemBean.get(i).getKeyName())) {
                            mCustomer = msystemBean.get(i).getKeyValue();
                            break;
                        }
                    }
                    if (!TextUtils.isEmpty(mCustomer)) {
                        Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                        Uri Urldata = Uri.parse("tel:" + mCustomer.replace("\\", ""));
                        mTelintent.setData(Urldata);
                        mContext.startActivity(mTelintent);
                    }
                } else {
                    mView.oninittell();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    //确认收货
    public void Receiving(){
        Params params=new Params();
        params.add("orderCode",mView.getTKOrder());
        mAuz.auzpost(UrlPool.POST_SHOP_RECEIVING, params, new AuzImpl.AuzListener() {
            @Override
            public void AuzSuccess(int code, String data) {
                if (code==0){
                    Toast toast = Toast.makeText(mContext, "操作成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                    initData();
                }else{
                    mView.onReceiving();
                }
            }

            @Override
            public void AuzFailure(int errorCode, String msg) {
                mView.onFailure(errorCode, msg);
            }
        });
    }

    public  void KtCopy() {
        // 获取系统剪贴板
        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(mContext.CLIPBOARD_SERVICE);
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
        ClipData clipData = ClipData.newPlainText(null, mDetailsBean.getOrder().getShopProductTravalling().getLogisticsNum());
        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData);

        Toast toast = Toast.makeText(mContext, "复制成功", Toast.LENGTH_SHORT);
        ToastUtils.showMyToast(toast, 3000);
    }

    public void Logistics(){
        if (!TextUtils.isEmpty(mDetailsBean.getOrder().getShopProductTravalling().getTravallingType())){
            Intent intent=new Intent();
            intent.setClass(mContext, LogisticsActivity.class);
            intent.putExtra("logistics_code",mDetailsBean.getOrder().getShopProductTravalling().getLogisticsNum());
            intent.putExtra("travalling_type",mDetailsBean.getOrder().getShopProductTravalling().getTravallingType());
            mContext.startActivity(intent);
        }else{
            Toast toast = Toast.makeText(mContext, "暂无物流信息，请稍后再查询", Toast.LENGTH_SHORT);
            ToastUtils.showMyToast(toast, 3000);
        }
    }


}
